import React, {Fragment, PureComponent} from 'react';
import { connect } from 'dva';
import { formatMessage, FormattedMessage } from 'umi/locale';
import {
  Form,
  Input,
  DatePicker,
  Select,
  Button,
  Card,
  InputNumber,
  Radio,
  Icon,
  Tooltip,
} from 'antd';
import router from 'umi/router';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import CodeHighlighter from 'braft-extensions/dist/code-highlighter';
import 'braft-extensions/dist/code-highlighter.css'
import 'prismjs/components/prism-java.min';
import 'prismjs/components/prism-sql.min';
import 'prismjs/components/prism-json.min';
import 'prismjs/components/prism-c.min';
import 'prismjs/components/prism-cpp.min';
import 'prismjs/components/prism-go.min';

import {editorUpload} from '@/utils/editorUpload';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from './CommitForm.less';

// 通过配置高亮显示支持语言
const options = {
  syntaxs: [
    {
      name: 'Java',
      syntax: 'java',
    }, {
      name: 'SQL',
      syntax: 'sql',
    },{
      name: 'C',
      syntax: 'c',
    },{
      name: 'C++',
      syntax: 'cpp',
    },{
      name: 'GO',
      syntax: 'go',
    },{
      name: 'JavaScript',
      syntax: 'javascript'
    }, {
      name: 'HTML',
      syntax: 'html'
    }, {
      name: 'CSS',
      syntax: 'css'
    }, {
      name: 'JSON',
      syntax: 'json'
    }
  ]
}
BraftEditor.use(CodeHighlighter(options))
const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TextArea } = Input;
// 富文本显示内容
const controls = [
  'undo', 'redo', 'split', 'font-size', 'indent', 'text-color', 'bold', 'italic', 'underline', 'strike-through',
  'superscript', 'subscript', 'remove-styles', 'text-align', 'split', 'headings', 'list_ul',
  'list_ol', 'blockquote', 'code', 'split', 'link', 'split', 'hr', 'split', 'media', 'clear'
];

@connect(({ loading }) => ({}))
@Form.create()
class CommitForm extends PureComponent {
  state = {
    taskContentId: "",
    answerRecordList: [{questionId: null, questionContent: ""}]
  };

  componentDidMount() {
    const {dispatch} = this.props;
    if(this.props.location.query.commitId){
      this.handleGetCommit(this.props.location.query.commitId,dispatch);
    }else if (this.props.location.query.taskId) {
      this.handleGetQuestion(this.props.location.query.taskId,dispatch);
    }else {
      // 获取当前正在提交的题目Id
      const taskId = 1;
      this.handleGetQuestion(taskId,dispatch);
    }
  }

  handleGetQuestion = (taskId,dispatch) =>{
    // 拉取题目信息
    dispatch({
      type: 'work/questions',
      payload: taskId,
      callback: res => {
        if (res.result) {
          const data = [];
          console.log(res.result.questionContentList.length)
          if(res.result.questionContentList != undefined && res.result.questionContentList != null && res.result.questionContentList.length >0){
            res.result.questionContentList.forEach(key => {
              data.push({questionId:key.id,questionContent:key.questionContent})
            });
            this.setState({
              taskName: `第${res.result.taskNumber}期，${res.result.taskSubject}`,
              answerRecordList: data,
              taskContentId: res.result.id,
            });
          }else {
            alert("数据异常!");
          }
        }else {
          alert("找不到题目记录!");
        }
      }
    });
  }

  handleGetCommit =(commitId,dispatch) =>{
    //拉取提交信息
    dispatch({
      type: 'work/getCommit',
      payload: commitId,
      callback: res => {
        if (res.result) {
          const data = [];
          if(res.result.answerRecordList != undefined && res.result.answerRecordList != null && res.result.answerRecordList.length >0){
            res.result.answerRecordList.forEach(key => {
              data.push({questionId:key.questionId,answerRecordId: key.id, questionContent:key.questionContent,answerContext: key.answerContext})
            });
            console.log(data);
            this.setState({
              taskName: "第5周讨论主题：Java基本编程语法",
              taskCommitId:  res.result.id,
              taskContentId: res.result.taskContentId,
              answerRecordList: data,
            });
          }else {
            alert("数据异常!");
          }
        }else {
          alert("找不到题目记录!");
        }
      }
    });
  }

  handleSubmit = e => {
    console.log("handleSubmit")
    const { dispatch, form } = this.props;
    const {taskContentId,answerRecordList} = this.state;
    e.preventDefault();
    let id,path;
    // if(current){
    //   id = current.id;
    //   path = 'work/update';
    // }else {
    //   id = null;
    //   path = 'work/add';
    // }
    const data ={answerRecordList:answerRecordList,commitType: 1,taskContentId }
    console.log(data)
    dispatch({
      type: "work/add",
      payload: data,
      callback: res => {
        alert(res.msg)
      }
    });

  };

  editorChange = (content, index) => {
    const data = this.state.answerRecordList;
    data[index].answerContext = content.toHTML();
    this.setState({answerRecordList: data});
  };

  editorConfig = (id,index) => {

    return {
      allowPasteImage: true, // 是否允许直接粘贴剪贴板图片（例如QQ截图等）到编辑器
      contentId: id,
      height:100,
      contentFormat: 'html',
      initialContent: '<p>请输入回答内容</p>',
      controls: controls,
      onChange: (content) => {
        this.editorChange(content, index);
      },
      media: {
        allowPasteImage: true,
        image: true,
        uploadFn: editorUpload
      }
    };
  };

  initQuestion = () => {
    const {
      form: { getFieldDecorator, getFieldValue },
    } = this.props;
    const {answerRecordList} = this.state;
    // 题目条目
    getFieldDecorator('keys', {initialValue: answerRecordList});
    const keys = getFieldValue('keys');
    return keys.map((k, index) => {
      return (
          <FormItem label={`题目${index + 1}:${k.questionContent}`}>
            <div key={'div' + k.questionId}>
              <BraftEditor {...this.editorConfig(k.questionId, index)} style={{border: "1px solid #d1d1d1" , borderRadius: 10}}/>
            </div>
          </FormItem>
      );
    });

  };

  render() {
    const { submitting } = this.props;

    const {
      form: { getFieldDecorator, getFieldValue },
    } = this.props;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 2 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
        md: { span: 20 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };

    const action = (
        <Fragment>
          <Button onClick={() => router.goBack()}>返回</Button>
          <Button type="primary" onClick={this.handleSubmit}>提交</Button>
        </Fragment>
    );

    return (
      <PageHeaderWrapper
        title="作业提交页面"
        content={this.state.taskName}
        action={action}
      >
        <Card bordered={false}>
          <Form hideRequiredMark style={{ marginTop: 8 }}>
            {this.initQuestion()}
          </Form>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default CommitForm;
